from flask import Blueprint, session, render_template, flash,  send_from_directory
from core.personal.form import PersonalForm, ProveForm, is_personal, submit_personal, is_prove, submit_prove
from models import User, to_img, Prove

personal_blueprint = Blueprint('personal', __name__)

def get_personal_img(uid):
   user = User.get_by_uid(uid)
   if user.img:
        return to_img(user.img)
   return None

def get_prove_img(uid):
    prove = Prove.get_by_uid(uid)
    if prove:
        return to_img(prove.img)
    return None

@personal_blueprint.route('/personal', methods=['GET', 'POST'])
def personal():
    uid = session.get('uid')
    form1 = PersonalForm()
    form2=ProveForm()

    # may be update user
    if is_personal(form1) :
        if submit_personal(form1,uid):
            flash('更新个人信息成功')
        else:
            flash('更新个人信息失败')

    if is_prove(form2) :
        if submit_prove(form2,uid):
            flash('上传身份证明成功')
        else:
            flash('上传身份证明失败')

    user = User.get_by_uid(uid)
    text = user.text
    role = user.role
    status = Prove.get_by_uid(uid).status
    unpass = Prove.get_by_uid(uid).unpass
    return render_template('personal/index.html',form1=form1,form2=form2,uid=uid,text=text,role=role,status=status,unpass=unpass)

# img需要的总是图像类型，不过可以通过路由获取
@personal_blueprint.route('/personal/user/img/<int:uid>')
def personal_user_img(uid):
    user = User.get_by_uid(uid)
    if user.img:
        return to_img(user.img)
    return send_from_directory('static', 'default.jpg', mimetype='image/jpeg')


@personal_blueprint.route('/personal/prove/img/<int:uid>')
def personal_prove_img(uid):
    prove = Prove.get_by_uid(uid)
    if prove.img:
        return to_img(prove.img)
    return send_from_directory('static', 'default.jpg', mimetype='image/jpeg')